<?php



declare (strict_types=1);



namespace app\beautiful\controller\cashier;

use app\BaseController;

use app\beautiful\helper\payment\PaymentMicropayHelper;

use app\beautiful\logic\LogsLogic;

use app\beautiful\logic\MemberWalletLogic;

use app\beautiful\logic\order\OrderCashierLogic;

use app\beautiful\logic\PartnerLogic;

use app\beautiful\logic\printer\PrinterLogic;

use app\beautiful\model\member\MemberCouponModel;

use app\beautiful\model\member\MemberModel;

use app\beautiful\model\order\CashierOrderItemModel;

use app\beautiful\model\order\CashierOrderModel;

use app\common\logic\DataLogic;

use think\facade\Db;



class Order extends BaseController{

    public function getOrderList()

    {

        $member_id=$this->request->param('member_id/d',0);

        $where=[

            ['shop_id','=',$this->request->shopId],

            ['is_delete','=',0],

        ];



        if(!empty($order_id)) $where[]=['order_id','=',$order_id];

        if($member_id != 0) $where[]=['member_id','=',$member_id];

        if(!empty($order_type)) $where[]=['order_type','=',$order_type];

        if(!empty($status)) $where[]=['status','=',$status];



        $order_model=new CashierOrderModel();

        $order_model=$order_model->with(['skus','member','partnerCommission']);



        $order=['add_time'=>'desc'];

        $field="*";

        $append=['add_time_format','pay_time_format','status_means','pay_type_mean'];

        $return = DataLogic::getDataList($order_model,$where,$order,$field,$this->request->limit,$this->request->page,$append);


        foreach ($return['list'] as $k => $list){

            $commission = 0;

            foreach ($list['partnerCommission'] as $key=>$value){

                $commission += $value['commission'];
            }
            unset($return['list'][$k]['partnerCommission']);
            //股东提成
            $return['list'][$k]['percentage'] = sprintf("%.2f",$commission);
            //商家实收
            $return['list'][$k]['boss_real_receive'] = sprintf("%.2f",$list['need_pay']  - $commission - $list['coupon_money']);
        }

        return $this->success($return);

    }



    public function getOrderDetail()

    {

        $order_id = $this->request->param('order_id/d',0);

        if($order_id==0) return $this->error('订单不存在#1');

        $order_model = new CashierOrderModel();

        $order_model = $order_model->with(['partnerCommission']);

        if(null === $order = $order_model->where(['order_id'=>$order_id])->find()) return $this->error('订单不存在#2');

        if($order->shop_id != $this->request->shopId) return $this->error('订单不存在#3');

        if($order->is_delete != 0) return $this->error('订单不存在#4');



        $member = MemberModel::find($order->member_id);



        $items=CashierOrderItemModel::where([

            ['shop_id','=',$this->request->shopId],

            ['order_id','=',$order_id]

        ])->select()->toArray();

        if(empty($items)) return $this->error('订单不存在#7');



        $order->append(['add_time_format','pay_time_format','status_means','pay_type_mean']);



        $commission = 0;

        foreach ($order->partnerCommission as $key=>$value){

            $commission += $value['commission'];
        }

        //股东提成
        $percentage = $commission;
        //商家实收
        $boss_real_receive = $order->need_pay - $order->freight - $commission - $order->coupon_money;


        $detail=[

            'order_id'=>$order->order_id,

            'add_time_format'=>$order->add_time_format,

            'status'=>$order->status,

            'status_means'=>$order->status_means,

            'need_pay'=>$order->need_pay,

            'pay_type'=>$order->pay_type,

            'pay_type_mean'=>$order->pay_type_mean,

            'pay_time_format'=>$order->pay_time_format,

            'total_price'=>$order->total_price,

            'youhui_balance'=>$order->youhui_price,

            'coupon_money'=>$order->coupon_money,

            'member'=>$member,

            'member_name'=>$member === null ? '-' :$member->nick_name,

            'member_mobile'=>$member === null ? '-' :$member->mobile,

            'items'=>$items,

            'percentage'=>sprintf("%.2f",$percentage),

            'boss_real_receive'=>sprintf("%.2f",$boss_real_receive),

        ];



        return $this->success(['detail'=>$detail]);

    }



    public function createOrder()

    {

        $member_id = $this->request->param('member_id/d',0);

        $total_price = $this->request->param('total_price/f',0);

        $coupon_id = $this->request->param('coupon_id/d',0);

        $youhui_price=$this->request->param('youhui_price/f',0);

        $goods=$this->request->param('goods/a',[]);

        $params=[

            'member_id'=>$member_id,

            'total_price'=>$total_price,

            'coupon_id'=>$coupon_id,

            'youhui_price'=>$youhui_price,

            'goods'=>$goods,

        ];

        Db::startTrans();

        try{



            $order_cashier_logic = new OrderCashierLogic($this->request->shopId);

            $order_id=$order_cashier_logic->createOrder($params);



            Db::commit();

            return $this->success(['order_id'=>$order_id]);

        } catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }

    }



    public function moneyPay()

    {

        $order_id = $this->request->param('order_id/d');

        if(empty($order_id)){

            return $this->error('请选择要支付的订单');

        }

        if( null === $order = CashierOrderModel::find($order_id)){

            return $this->error('订单不存在');

        }

        if($order->status != 1 || $order->is_delete == 1){

            return $this->error('订单不在未支付状态');

        }

        if($order->member_id == 0){

            return $this->error('游客不能使用余额支付#1');

        }

        if(null === $member = MemberModel::find($order->member_id)){

            return $this->error('游客不能使用余额支付#2');

        }

        if($member->shop_id != $this->request->shopId){

            return $this->error('游客不能使用余额支付#3');

        }

        Db::startTrans();

        try{

            if(!empty($order->member_coupon_id)){

                if(null === $myCoupon = MemberCouponModel::find($order->member_coupon_id)){

                    Db::rollback();

                    return $this->error('优惠券不存在');

                }

                if($myCoupon->status == 1){

                    Db::rollback();

                    return $this->error('优惠券不存在');

                }

                $myCoupon->status = 1;

                $myCoupon->save();

                LogsLogic::coupon($this->request->shopId, $order->member_id, -1, 12, $order->member_coupon_id, '', 0);

            }

            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $member->member_id);



            $needPay = round(($order->total_price * 100 +  - $order->coupon_money * 100 - $order->youhui_price * 100)/100,2);

            if($needPay < 0){

                Db::rollback();

                $this->error('支付金额不正确');

            }

            if($needPay!=0){

                $res = $MemberWalletLogic->useBalance($needPay, $order->total_price , 8); //商城购物使用

                if($res == false){

                    Db::rollback();

                    return $this->error($MemberWalletLogic->getError());

                }

            }



            $order->pay_time = time();

            $order->status = 2; //订单的状态值

            $order->pay_type = 'money';

            $order->save();



            $this->usePrinter($order);

            //分销记录

//            $PartnerLogic = new PartnerLogic($order->shop_id);

//            $PartnerLogic->commission($order->member_id,$needPay);

             //分红
             $PartnerLogic = new PartnerLogic($order->shop_id);

             $PartnerLogic->commissionNew($order->member_id,$needPay,'cashierOrder',$order_id);



            Db::commit();

            return $this->success('余额支付成功');

        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }

    }



    public function cashPay()

    {

        $order_id = $this->request->param('order_id/d');

        if(empty($order_id)){

            return $this->error('请选择要支付的订单');

        }

        if( null === $order = CashierOrderModel::find($order_id)){

            return $this->error('订单不存在');

        }

        if($order->status != 1 || $order->is_delete == 1){

            return $this->error('订单不在未支付状态');

        }

        if($order->member_id != 0){

            if(null === $member = MemberModel::find($order->member_id)){

                return $this->error('会员不存在');

            }

            if($member->shop_id != $this->request->shopId){

                return $this->error('会员不存在');

            }

        }



        Db::startTrans();

        try{

            if($order->member_id != 0){

                if(!empty($order->member_coupon_id)){

                    if(null === $myCoupon = MemberCouponModel::find($order->member_coupon_id)){

                        Db::rollback();

                        return $this->error('优惠券不存在');

                    }

                    if($myCoupon->status == 1){

                        Db::rollback();

                        return $this->error('优惠券不存在');

                    }

                    $myCoupon->status = 1;

                    $myCoupon->save();

                    LogsLogic::coupon($this->request->shopId, $order->member_id, -1, 12, $order->member_coupon_id, '', 0);

                }

            }



            $needPay = round(($order->total_price * 100 +  - $order->coupon_money * 100 - $order->youhui_price * 100)/100,2);

            if($needPay <= 0){

                Db::rollback();

                $this->error('支付金额不正确');

            }

            $order->pay_time = time();

            $order->status = 2; //订单的状态值

            $order->pay_type = 'cash';

            $order->save();



            $this->usePrinter($order);



            //分销记录

            //$PartnerLogic = new PartnerLogic($order->shop_id);

            //$PartnerLogic->commission($order->member_id,$needPay);

            //分红

            $PartnerLogic = new PartnerLogic($order->shop_id);

            $PartnerLogic->commissionNew($order->member_id,$needPay,'cashierOrder',$order_id);



            Db::commit();

            return $this->success('现金支付成功');

        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }

    }



    public function scanPay()

    {

        $auth_code=$this->request->param('auth_code');

        $order_id=$this->request->param('order_id');

        if(empty($order_id)){

            return $this->error('请选择要支付的订单');

        }

        if( null === $order = CashierOrderModel::find($order_id)){

            return $this->error('订单不存在');

        }

        if($order->status != 1 || $order->is_delete == 1){

            return $this->error('订单不在未支付状态');

        }

        try{

            $payment = new PaymentMicropayHelper($this->request->shopId);

            $return =$payment->sendPayment([

                'product_name'=>'扫码支付',

                'order_id'=>$order_id,

                'need_pay'=>$order->need_pay,

                'auth_code'=>$auth_code,

            ]);

            if($return['return_code'] === 'SUCCESS'){

//            if($return['result_code'] === 'SUCCESS'){

//

//            }else{

//                return $this->error($return['err_code_des']);

//            }

                //分销记录

                //$PartnerLogic = new PartnerLogic($order->shop_id);

                //$PartnerLogic->commission($order->member_id,$order->need_pay);

                //分红

                $PartnerLogic = new PartnerLogic($order->shop_id);

                $PartnerLogic->commissionNew($order->member_id,$order->need_pay,'cashierOrder',$order_id);

                return $this->success($return);

            }

            return $this->error($return['return_msg']);

        } catch(\Exception $e){

            return $this->error($e->getMessage());

        }

    }



    public function queryOrder()

    {

        $order_id=$this->request->param('order_id');

        if(empty($order_id)){

            return $this->error('请选择要支付的订单');

        }

        if( null === $order = CashierOrderModel::find($order_id)){

            return $this->error('订单不存在');

        }

        if($order->status != 1 || $order->is_delete == 1){

            return $this->error('订单不在未支付状态');

        }



        try {

            $payment = new PaymentMicropayHelper($this->request->shopId);

            $return =$payment->queryOrder($order_id);

            if($return['return_code'] === 'SUCCESS'){

                if($return['result_code'] === 'SUCCESS'){

                    if($return['trade_state'] === 'SUCCESS'){

                        $order->pay_time = time();

                        $order->pay_type = 'weixin';

                        $order->status=2;

                        $order->save();

                        $this->usePrinter($order);

                    }

                }

                return $this->success($return);

            }

            return $this->error($return['return_msg']);

        }catch(\Exception $e){

            return $this->error($e->getMessage());

        }

    }



    public function cancelPay()

    {

        $order_id=$this->request->param('order_id');

        if(empty($order_id)){

            return $this->success('成功');

        }

        if( null === $order = CashierOrderModel::find($order_id)){

            return $this->success('成功');

        }

        if($order->status != 1 || $order->is_delete == 1){

            return $this->success('成功');

        }



        $payment = new PaymentMicropayHelper($this->request->shopId);

        $return =$payment->cancelPay($order_id);



        $order->status=-1;

        $order->save();

        return $this->success('成功');



    }



    public function cancelOrder()

    {

        $order_id=$this->request->param('order_id');

        if(empty($order_id)){

            return $this->error('请选择要支付的订单');

        }

        if( null === $order = CashierOrderModel::find($order_id)){

            return $this->error('订单不存在');

        }

        if($order->status != 1 || $order->is_delete == 1){

            return $this->error('订单不在未支付状态');

        }



        $order->status=-1;

        $order->save();

        return $this->success('成功');

    }



    protected function usePrinter($order)

    {

        //打印机

        $printer_logic =new PrinterLogic($this->request->shopId);

        $printer_logic->print('cashOrder',$order->order_id);

    }

}

